package cn.cloudreal.cbms.system.action;

import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import cn.cloudreal.cbms.common.util.Constants;
import cn.cloudreal.cbms.common.util.DatadicContext;
import cn.cloudreal.cbms.system.service.OrganizaService;
import cn.cloudreal.cbms.vo.Dictionary;
import cn.cloudreal.cbms.vo.Organiza;
import cn.cloudreal.cbms.vo.UserInfo;

import com.opensymphony.xwork2.ActionSupport;

/**
 * <p>
 * Title: CBMS
 * </p>
 * <p>
 * Description:组织架构管理查询数据服务层视图类
 * </p>
 * <p>
 * Copyright: Copyright (c) 2012
 * </p>
 * <p>
 * Company:云恒瑞通
 * </p>
 * 
 * @author Gaoxuejiao
 * @date 2012-07-17
 */
public class OrganizaAction extends ActionSupport
{
    /** serialVersionUID */
    private static final long serialVersionUID = 1L;

    /** 日志工具类实例 */
    private static final Logger log = Logger.getLogger(OrganizaAction.class);

    /**
     * 注入service 类
     */
    private OrganizaService organizaService;

    /** 组织架构列表 */
    private List<Organiza> organizaLists;

    /**
     * 用户实体信息
     */
    private Organiza organiza;

    /** falg：1：查看，2：修改初始化，3：修改确认 ，4：新增保存 */
    String flag;

    /**
     * 列表
     * 
     * @return String
     */
    public String getOrganizaList()
    {
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter OrganizaAction list() method,return String");
        }
        try
        {
            // 查询组织架构信息 获取当前节点集合
            organizaLists = new ArrayList<Organiza>();

            // 获取当前session对象中所属城市
            UserInfo userInfo = (UserInfo) ServletActionContext.getRequest()
                    .getSession()
                    .getAttribute(Constants.SESSIONPRKEY);

            // 非空判断 当前用户城市编码是否为空
            if (null != userInfo && null != userInfo.getUsercity())
            {
                organizaLists = organizaService.getOrganizaByCity(userInfo.getUsercity());
            }
            else
            {
                organizaLists = organizaService.getOrganizaByCity("DG");
            }

            if (null != organizaLists && organizaLists.size() > 0)
            {
                organiza = organizaLists.get(0);
                // 数字典获取数据
                Dictionary dic = DatadicContext.getInstance()
                        .getDatadicObject(organiza.getCity(),
                                Constants.CITY_AREA_CODE);

                if (null != dic)
                {
                    organiza.setCity(dic.getClassname());
                }
            }

            // 获取生成组织架构字符串
            flag = Constants.getOrganizaTree(organizaLists);
        }
        catch (Exception e)
        {
            // TODO: handle exception 添加异常信息 返回error
            log.error("Error OrganizaAction list() method,return String", e);
            return ERROR;
        }

        // 打印退出方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Exit OrganizaAction list() method,return String");
        }
        return SUCCESS;
    }

    /**
     * 查看
     * 
     * @return
     */
    public String organizaDetail()
    {
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter OrganizaAction view() method,return String");
        }
        // response 对象
        HttpServletResponse response = ServletActionContext.getResponse();
        PrintWriter out = null;
        try
        {
            // 获取PrintWriter对象
            ServletActionContext.getRequest()
                    .setCharacterEncoding(Constants.STR_UTF);
            response.setContentType(Constants.STR_CHARSET);
            out = response.getWriter();
            // 如果不为空 执行查询
            if (null != organiza && null != organiza.getOrgCode())
            {
                String code = URLDecoder.decode(organiza.getOrgCode(), "UTF-8");
                organiza.setOrgCode(code);
                organiza = organizaService.getOrganizaByCode(organiza.getOrgCode());

                if (null != organiza && null != organiza.getCity())
                {
                    // 数字典获取数据
                    Dictionary dic = DatadicContext.getInstance()
                            .getDatadicObject(organiza.getCity(),
                                    Constants.CITY_AREA_CODE);
                    if (null != dic)
                    {
                        organiza.setCity(dic.getClassname());
                    }
                }

                Map map = new HashMap<Object, Object>();
                map.put("organiza", organiza);

                JSONArray jo = JSONArray.fromObject(map);

                out.print(jo.toString());
                out.flush();
                out.close();
                return null;
            }
        }
        catch (Exception e)
        {
            // TODO: handle exception 添加异常日志
            log.error("Error OrganizaAction view() method,return String edit",
                    e);
            out.print("error");
            out.flush();
            out.close();
            return null;
            // return ERROR;
        }
        return SUCCESS;
    }

    /**
     * 执行修改
     * 
     * @return SUCCESS
     */
    public String doOrganizaEdit()
    {
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter OrganizaAction doorganizaEdit() method,return String");
        }
        // response 对象
        HttpServletResponse response = ServletActionContext.getResponse();
        PrintWriter out = null;
        try
        {
            // 获取PrintWriter对象
            ServletActionContext.getRequest()
                    .setCharacterEncoding(Constants.STR_UTF);
            response.setContentType(Constants.STR_CHARSET);
            out = response.getWriter();

            if (null != organiza)
            {
                // 截取字符串哇
                String temp = organiza.getOrgCode().trim();
                String[] tempStr = temp.split(",");
                if (tempStr.length > 1)
                {
                    organiza.setOrgCode(tempStr[1].trim());
                }
                // 默认当前登录人地市
                UserInfo userSession = (UserInfo) ServletActionContext.getRequest()
                        .getSession()
                        .getAttribute("logUser");
                organiza.setCity(userSession.getUsercity());

                organizaService.updateOrganiza(organiza);
                out.print("true");
                out.flush();
                out.close();
                return null;
            }
        }
        catch (Exception e)
        {
            // TODO: handle exception 添加异常日志
            log.error("Error OrganizaAction doorganizaEdit() method,return String edit",
                    e);
            // return ERROR;
            out.print("error");
            out.flush();
            out.close();
            return null;
        }
        return SUCCESS;
    }

    /**
     * 判断节点当名称是否已经存在
     * 
     * @return SUCCESS
     */
    public String isExistUseOrgName()
    {
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter OrganizaAction isExistUseOrgCode() method,return String");
        }
        // response 对象
        HttpServletResponse response = ServletActionContext.getResponse();
        PrintWriter out = null;
        try
        {
            // 获取PrintWriter对象
            ServletActionContext.getRequest()
                    .setCharacterEncoding(Constants.STR_UTF);
            response.setContentType(Constants.STR_CHARSET);
            out = response.getWriter();

            // 如果不为空 执行查询
            if (null != organiza)
            {
                String code = URLDecoder.decode(organiza.getOrgName(), "UTF-8");
                organiza.setOrgName(code);

                // 获取当前session对象中所属城市
                UserInfo userInfoTemp = (UserInfo) ServletActionContext.getRequest()
                        .getSession()
                        .getAttribute(Constants.SESSIONPRKEY);

                // 设置城市条件
                organiza.setCity(userInfoTemp.getUsercity());

                List<Organiza> orgList = organizaService.getOrganizas(organiza);
                // 验证当前组织节点是否已经存在
                if (null != orgList && orgList.size() > 0)
                {
                    out.print("true");
                    out.flush();
                    out.close();
                    return null;
                }
            }
        }
        catch (Exception e)
        {
            // TODO: handle exception 添加异常日志
            log.error("Error OrganizaAction isExistUseOrgCode() method,return String edit",
                    e);
            out.print("error");
            out.flush();
            out.close();
            // return ERROR;
        }
        return null;
    }

    /**
     * 判断节点当前是否有人在使用
     * 
     * @return SUCCESS
     */
    public String isExistUseOrgCode()
    {
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter OrganizaAction isExistUseOrgCode() method,return String");
        }
        // response 对象
        HttpServletResponse response = ServletActionContext.getResponse();
        PrintWriter out = null;
        try
        {
            // 获取PrintWriter对象
            ServletActionContext.getRequest()
                    .setCharacterEncoding(Constants.STR_UTF);
            response.setContentType(Constants.STR_CHARSET);
            out = response.getWriter();

            // 如果不为空 执行查询
            if (null != organiza)
            {
                String code = URLDecoder.decode(organiza.getOrgCode(), "UTF-8");
                organiza.setOrgCode(code);
                List<Organiza> orgList = organizaService.getOrganizas(organiza);
                // 验证当前组织节点是否已经存在
                if (null != orgList && orgList.size() > 0)
                {
                    out.print("true");
                    out.flush();
                    out.close();
                    return null;
                }
            }
        }
        catch (Exception e)
        {
            // TODO: handle exception 添加异常日志
            log.error("Error OrganizaAction isExistUseOrgCode() method,return String edit",
                    e);
            out.print("error");
            out.flush();
            out.close();
            return null;
            // return ERROR;
        }
        return SUCCESS;
    }

    /**
     * 删除
     * 
     * @return SUCCESS
     */
    public String deleteOrganiza()
    {
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter OrganizaAction deleteOrganiza() method,return String");
        }

        // response 对象
        HttpServletResponse response = ServletActionContext.getResponse();
        PrintWriter out = null;
        try
        {
            // 获取PrintWriter对象
            ServletActionContext.getRequest()
                    .setCharacterEncoding(Constants.STR_UTF);
            response.setContentType(Constants.STR_CHARSET);
            out = response.getWriter();
            // 如果不为空 执行查询
            if (null != organiza && null != organiza.getOrgCode())
            {
                String code = URLDecoder.decode(organiza.getOrgCode(), "UTF-8");
                organiza.setOrgCode(code);

                // if (organizaService.isParentOrg(organiza.getOrgCode()))
                // {
                // out.print("当前是父节点，暂不能删除！");
                // out.flush();
                // out.close();
                // return null;
                // }
                // else
                if (organizaService.isUseByUser(organiza.getOrgCode()))
                {
                    // 验证当前组织节点是否正在使用
                    out.print("false");
                    out.flush();
                    out.close();
                    return null;
                }
                else
                {
                    // 执行删除
                    organizaService.delOrganiza(organiza);
                    out.print("true");
                    out.flush();
                    out.close();
                    return null;
                }

            }
        }
        catch (Exception e)
        {
            // TODO: handle exception 添加异常日志 返回Error
            log.error("Error OrganizaAction deleteOrganiza() method,return String",
                    e);
            out.print("error");
            out.flush();
            out.close();
            return null;
        }

        // 打印退出方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Exit OrganizaAction delete() method,return String ");
        }
        return null;
    }

    /**
     * 执行新增
     * 
     * @return SUCCESS
     */
    public String doAddOrganiza()
    {
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter OrganizaAction doAddorganiza() method,return String");
        }

        // response 对象
        HttpServletResponse response = ServletActionContext.getResponse();
        PrintWriter out = null;
        try
        {
            // 获取PrintWriter对象
            ServletActionContext.getRequest()
                    .setCharacterEncoding(Constants.STR_UTF);
            response.setContentType(Constants.STR_CHARSET);
            out = response.getWriter();

            // 获取当前session对象中所属城市
            UserInfo userInfo = (UserInfo) ServletActionContext.getRequest()
                    .getSession()
                    .getAttribute(Constants.SESSIONPRKEY);

            // 非空判断
            if (null != organiza && null != organiza.getOrgCode())
            {
                String temp = organiza.getOrgCode().trim();
                String[] tempStr = temp.split(",");
                if (tempStr.length > 0)
                {
                    organiza.setOrgCode(tempStr[0].trim());
                }

                if (null != userInfo && null != userInfo.getUsercity())
                {
                    organiza.setCity(userInfo.getUsercity());
                }
                else
                {
                    organiza.setCity("DG");
                }
                int result = organizaService.addOrganiza(organiza);
                if (result != 0)
                {
                    out.print("true");
                    out.flush();
                    out.close();
                    return null;
                }
            }
        }
        catch (Exception e)
        {
            // TODO: handle exception
            // 打印方法体异常日志
            log.error("Error OrganizaAction doAddorganiza() method,return String ",
                    e);
            // return ERROR;
            out.print("error");
            out.flush();
            out.close();
            return null;
        }

        // 打印退出方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Exit OrganizaAction doAddorganiza() method,return String ");
        }
        return SUCCESS;
    }

    public String getFlag()
    {
        return flag;
    }

    public void setFlag(String flag)
    {
        this.flag = flag;
    }

    public List<Organiza> getOrganizaLists()
    {
        return organizaLists;
    }

    public void setOrganizaLists(List<Organiza> organizaLists)
    {
        this.organizaLists = organizaLists;
    }

    public Organiza getOrganiza()
    {
        return organiza;
    }

    public void setOrganiza(Organiza organiza)
    {
        this.organiza = organiza;
    }

    public OrganizaService getOrganizaService()
    {
        return organizaService;
    }

    public void setOrganizaService(OrganizaService organizaService)
    {
        this.organizaService = organizaService;
    }

}
